﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace Wiyan.Code.PowerMSNRobotLibrary.Utility
{
    public class IPResolver
    {
        public static IPAddress GetMyInternalIP()
        {
            string myHost = Dns.GetHostName();
            IPAddress[] address = Dns.GetHostEntry(myHost).AddressList;

            for (int i = 0; i < address.Length; i++)
            {
                if (address[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return address[i];
                }
            }

            return IPAddress.Loopback;
        }

        public static IPAddress GetMyExternalIP(ref string error)
        {
            string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp";
            WebClient wc = new WebClient();  
            UTF8Encoding utf8 = new UTF8Encoding();
            string requestHtml = "";
            error = string.Empty;

            try
            {
                requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
            }
            catch (WebException)
            {
                // do something with exception
                return null;
            }

            IPAddress address = null;
            if (IPAddress.TryParse(requestHtml, out address) == false)
            {
                error = string.Format("Error parse IP address from whatismyip.com automation system. Detail:{0}", requestHtml);
            }

            return address;
        }
    }
}
